package com.xilihui.xlh.business.fragments;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xilihui.xlh.R;
import com.xilihui.xlh.business.activitys.HomeActivity;
import com.xilihui.xlh.business.activitys.LoginActivity;
import com.xilihui.xlh.business.activitys.MsgActivity;
import com.xilihui.xlh.business.adapters.AssistanAdapter;
import com.xilihui.xlh.business.entities.AgentsEntity;
import com.xilihui.xlh.business.entities.HomeEntity;
import com.xilihui.xlh.business.requests.HomeRequest;
import com.xilihui.xlh.business.widget.WithdrawPopWindow;
import com.xilihui.xlh.component.recyclerview.BaseAdapter;
import com.xilihui.xlh.component.recyclerview.BaseViewHolder;
import com.xilihui.xlh.component.recyclerview.LinearLayoutColorDivider;
import com.xilihui.xlh.core.app.BaseApplication;
import com.xilihui.xlh.core.app.BaseCompatFragment;
import com.xilihui.xlh.core.exception.DefaultExceptionListener;
import com.xilihui.xlh.core.exception.ExceptionManager;
import com.xilihui.xlh.core.http.DoTransform;
import com.xilihui.xlh.core.http.HttpSubscriber;
import com.xilihui.xlh.core.util.LogUtil;
import com.xilihui.xlh.core.util.SPUtil;
import com.xilihui.xlh.core.util.ToastUtil;
import com.xilihui.xlh.core.util.YEventBuses;

import org.feezu.liuli.timeselector.Utils.TextUtil;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/5/16.
 */

public class AssistantFragment extends BaseCompatFragment implements OnRefreshListener, OnLoadMoreListener, View.OnClickListener {

    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.iv_msg)
    ImageView iv_msg;
    
    ExceptionManager exceptionManager;
    AssistanAdapter assistanAdapter;
    
    ArrayList<HomeEntity.BannerBean> bannerData = new ArrayList<>();
    ArrayList<AgentsEntity> datas = new ArrayList<>();
    
    int page = 1;
    String lat = "";
    String lng = "";
    
    String sign_status = "";
    
    @OnClick(R.id.iv_msg)
    public void msg(){
        if(isLogin()){
            startActivity(new Intent(getContext(), MsgActivity.class));
        }else {
            startActivity(new Intent(getContext(), LoginActivity.class));
        }
        
    }
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_assistant,container,false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        YEventBuses.register(this);
        
        exceptionManager = new ExceptionManager(smartRefreshLayout,new DefaultExceptionListener(this));
        
        smartRefreshLayout.setOnRefreshListener(this);
        smartRefreshLayout.setOnLoadMoreListener(this);
        
        assistanAdapter = new AssistanAdapter(getContext());
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(assistanAdapter);

        lat = (String) SPUtil.get(getContext(),SPUtil.LAT,"0");
        lng = (String)SPUtil.get(getContext(),SPUtil.LNG,"0");
        getHome(true,page);
        
    }
    
    public void getHome(boolean isLoading, final int page){
        HomeRequest.getHome(getContext(),lat,lng,page)
                .compose(DoTransform.<HomeEntity>applyScheduler(getActivity(),isLoading))
                .subscribe(new HttpSubscriber<HomeEntity>((FragmentActivity)getActivity()) {
                    @Override
                    protected void onSuccess(HomeEntity entity) {
                        
                        if(page==1){
                            datas.clear();
                            if(bannerData!=null&&bannerData.size()>0){
                                bannerData.clear();
                            } 
                            bannerData = (ArrayList<HomeEntity.BannerBean>) entity.getBanner();
                            assistanAdapter.setBanner(bannerData);
                            exceptionManager.hide();
                            sign_status = entity.getSign_status();
                            String token = (String)SPUtil.get(getActivity(),SPUtil.TOKEN,"");
                            if (TextUtil.isEmpty(sign_status)&&!TextUtil.isEmpty(token)){
                                YEventBuses.post(new YEventBuses.Event("ReLogin"));
                                SPUtil.put(BaseApplication.get(), SPUtil.IS_LOGIN_ACTIVITY_OPEN,true);
                                SPUtil.put(BaseApplication.get(),SPUtil.IS_LOGIN,false);
                                SPUtil.put(BaseApplication.get(),SPUtil.TOKEN,"");
                            }
                            assistanAdapter.setSingStatus(sign_status);
                            
                            if(bannerData.size()<1&&entity.getAgents().size()<1){
                                exceptionManager.showEmpty();
                            }else {
                                exceptionManager.hide();
                            }
                            
                        }

                        datas.addAll(entity.getAgents());
                        assistanAdapter.setDatas(datas);
                        smartRefreshLayout.finishRefresh();
                        smartRefreshLayout.finishLoadMore();

                        if(page>=entity.getPageCount()){
                            smartRefreshLayout.finishLoadMoreWithNoMoreData();
                        }else {
                            smartRefreshLayout.setNoMoreData(false);
                        }

                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.toastShortNegative(msg);
                        smartRefreshLayout.finishRefresh();
                        smartRefreshLayout.finishLoadMore();
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Subscribe
    public void onEventMainThread(YEventBuses.Event event) {
        if(event.is("login_")){
            LogUtil.i("mylog","home 刷新");
            page = 1;
            getHome(false,page);
        }
    }

    @Override
    public void onDestroy() {
        YEventBuses.unregister(this);
        super.onDestroy();
    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        getHome(false,page);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page = page + 1;
        getHome(false,page);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv:
                page = 1;
                getHome(true,page);
                break;
        }
    }

    public boolean isLogin(){
        return (boolean) SPUtil.get(getContext(),SPUtil.IS_LOGIN,false);
    }
    
    
}
